import React, { useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { WebView } from 'react-native-webview';
import { useAsyncEffect } from 'ahooks';
import to from '../../../utils/to.ts';
import LocationClass from '../../../utils/LocationClass.ts';
import Tools from '../../../utils/Tools.ts';

interface ISelectMapPointProps {
  navigation: NavigationProp<any, 'selectMapPoint'>;
  route: RouteProp<{ selectMapPoint: { backScreen: string } }, 'selectMapPoint'>;
}
const SelectMapPoint: React.FC<ISelectMapPointProps> = ({ navigation, route }) => {
  const [position, setPosition] = useState<{ lat: number; lng: number } | undefined>(undefined);
  useAsyncEffect(async () => {
    const [err, res] = await to(LocationClass.getLocation());
    if (err) return;
    setPosition(Tools.gpsCoordinateToBaiduCoordinate(res.coords.longitude, res.coords.latitude));
  }, []);

  /**
   * 处理来自 WebView 的消息
   * @param event
   */
  const handleWebViewMessage = async (event: any) => {
    const message = event.nativeEvent.data;
    const params = navigation.getState().routes.find((route) => route.name === route.params?.backScreen)?.params;
    if (params) {
      navigation.navigate(route.params.backScreen, { ...params, message });
    } else {
      navigation.navigate(route.params.backScreen, { message });
    }
  };

  return (
    <>
      <WebView source={{ uri: `https://kics.kanglailab.com/baiduMapPosition?lng=${position?.lng}&lat=${position?.lat}` }} onMessage={handleWebViewMessage} />
    </>
  );
};

export default SelectMapPoint;
